package com.qst;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

@SuppressWarnings("all")
public class Db {
	private static String url = "jdbc:mysql://localhost:3306/mbti?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true";
	// userName和password 可选填,不写默认从src/main/resources/jdbc.properties中读取
	private static String userName = "";
	private static String password = "";
	private static void loadDBProperties() {
		Properties prop = new Properties();
		InputStream inputStream = null;

		try {
			// 使用类加载器来加载资源文件
			inputStream = Db.class.getClassLoader().getResourceAsStream("jdbc.properties");
			if (inputStream == null) {
				throw new IOException("jdbc.properties file not found in classpath");
			}
			// 加载属性文件
			prop.load(inputStream);
			// 读取配置
			userName = prop.getProperty("username");
			password = prop.getProperty("password");

		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	static {
			try {
				if (userName == "" && password == ""){
					loadDBProperties();
				}
				com.mysql.jdbc.Driver.class.newInstance();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

	}
	public static Connection getConnection() throws SQLException {

		Connection conn = DriverManager.getConnection(url, userName, password);
		conn.setAutoCommit(true);
		return conn;
	}

	public static int getGeneratedInt(Statement stmt) throws SQLException {
		ResultSet rs = stmt.getGeneratedKeys();
		rs.next();
		return rs.getInt(1);

	}

}
